package com.huishou.lajiMain.config;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObjectSummary;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/*
 * @Author:大力王
 * @Date:2024/5/10-10-23:15
 * 开始了
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
@Slf4j
public class OssConfig {
    private String endpoint;
    private String accessKeyId;
    private String secretAccessKey;
    private String bucketName;

    public OSS getOSSClient() {
        return new OSSClientBuilder().build("https://"+endpoint,accessKeyId,secretAccessKey);
    }

    /**
      通用上传文件
      @param file 文件
     * @param fileType 存放位置
     * @return 上传成功文件地址
     * @throws IOException 流异常
     */
    public String uploadFile(MultipartFile file, String fileType) throws IOException {
        OSS ossClient = getOSSClient();
//      获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
//      创建一个日期时间格式器，用于格式化为"yyyyMMdd"
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
//      格式化当前日期和时间
        String date = now.format(formatter);
//      hutool获取uuid作为文件名
        String simpleUUID = IdUtil.simpleUUID();
//      获取file 文件后缀
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
//      上传路径+文件名
        String fileName = fileType + "/" + date + "/" + simpleUUID + "." + suffix;
//      获取上传文件的输入流
        InputStream inputStream = file.getInputStream();
//      调用OSS SDK的提交文件
        ossClient.putObject(bucketName, fileName, inputStream);
//      断开连接
        ossClient.shutdown();
        return "https://"+bucketName+"."+endpoint+"/"+fileName;
    }

    /**
     * 下载文件
     * @param objectName 文件名称
     * @return 下载文件成功
     */
    public ByteArrayOutputStream getObject(String objectName) throws Exception {
//       获取链接
        OSS ossClient = getOSSClient();
//        获取文件输入流
        InputStream inputStream = ossClient.getObject(bucketName, objectName).getObjectContent();
//        输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 1.9+ 的正确写法
        byte[] buffer = inputStream.readAllBytes();
        outputStream.write(buffer);
        //1.8的写法 while循环获取
//        byte[] buffer = new byte[1024];
//        int bytesRead;
//        while ((bytesRead = inputStream.read(buffer)) != -1) {
//            outputStream.write(buffer, 0, bytesRead);
//        }
//        断开连接
        ossClient.shutdown();
        return outputStream;
    }
    /**
     * 清理过期oss文件对象
     */
    public void clearExpiredObjects() {
        OSS ossClient = getOSSClient();
        // 计算过期时间（假设为一周前）
        long expirationTimeMillis = (60 * 60 * 1000);
        // 清理过期的OSS对象
        List<OSSObjectSummary> objectSummaries = ossClient.listObjects(bucketName).getObjectSummaries();
        for (OSSObjectSummary objectSummary : objectSummaries) {
            Date lastModified = objectSummary.getLastModified();
            if (lastModified != null && lastModified.getTime() < expirationTimeMillis) {
                ossClient.deleteObject(bucketName, objectSummary.getKey());
                log.info("Deleted expired OSS object: " + objectSummary.getKey());
            }
        }
        //        断开连接
        ossClient.shutdown();
    }
}
